<?php
namespace app\common\component\user_wallet;

use think\Session;

class UserWalletService {
	public function getUserWallet($user_id = null) {
		if(!$user_id) {
			$user_id = Session::get('user_id');
		}

		$getUserWallet = UserWalletModel::get($user_id);

		if(!$getUserWallet) {

			$resultUserWallet = $this -> create([
				'user_id' => $user_id,
				'money' => 0,
				'withdraw_position' => 0
			]);

			if($resultUserWallet['code'] === 0) {
				$getUserWallet = $resultUserWallet['data']['user_wallet'];
			} else {
				$getUserWallet = null;
			}
		}

		if($getUserWallet) {
			return [
				'code' => 0,
				'data' => [
					'user_wallet' => $getUserWallet
				]
			];
		}

		return [
			'code' => -1,
			'message' => '失败'
		];
		
	}

	public function create($data) {
		$userWalletModel = new UserWalletModel($data);

    	if($userWalletModel -> save()) {
    		return [
    			'code' => 0,
    			'message' => '创建成功',
    			'data' => [
    				'user_wallet' => $userWalletModel
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '创建失败'
		];
	}

	public function update($data, $user_id = null) {
    	$userWalletModel = new UserWalletModel();

    	if($user_id && $user_id > 0) {
    		$updateUserWallet = $userWalletModel -> where('user_id', $user_id) -> update($data);
    	} else if(Session::has('user_id')) {
    		$updateUserWallet = $userWalletModel -> where('user_id', Session::get('user_id')) -> update($data);
    	} else {
    		$updateUserWallet = false;
    	}

    	if($updateUserWallet) {
    		return [
    			'code' => 0,
    			'message' => '钱包修改成功'
    		];
    	}

    	return [
			'code' => -1,
			'message' => '钱包修改失败'
		];
    }

	// 加Money
	public function setIncMoney($money, $user_id = null) {
		if(!$user_id) {
			$user_id = Session::get('user_id');
		}

		if((new UserWalletModel) -> where('user_id', $user_id) -> setInc('money', $money)) {
			return [
    			'code' => 0,
    			'message' => '增加钱包成功',
    		];
		}

		return [
			'code' => -1,
			'message' => '增加钱包失败',
		];
	}

	// 减Money
	public function setDecMoney($money, $user_id = null) {
		if(!$user_id) {
			$user_id = Session::get('user_id');
		}

		if((new UserWalletModel) -> where('user_id', $user_id) -> setDec('money', $money)) {
			return [
    			'code' => 0,
    			'message' => '扣除成功',
    		];
		}

		return [
			'code' => -1,
			'message' => '扣除失败',
		];
	}
}
?>